<template>
	<view class="pageBox">
		<view class="videoBox">
			<video id="myVideo" :src="data.liveUrl" enable-danmu 
				:autoplay="data.isAutoPlay" 
				@ended="videoEndClick" class="videoBox"></video>

			<cover-view class="person">
				在线：{{watchNumUnit}}人
			</cover-view>
		</view>
		<view class="videoMenu">
			<view class="videoMenu_item" v-for="(item,index) in menu" :key="item" :class="{active:data.nowIndex==index}"
				@click="menuFun(index)">
				{{item}}
			</view>
		</view>
		<view class="chatHome" v-if="data.nowIndex == 0" style="padding-top: 20rpx;">
			<template v-if="data.liveInfo?.playbackActivity !== '0'">
				<view class="questionList" v-for="item in data.questionList" :key="item.id">
					<view class="title">{{item.content}}</view>
					<view class="option" v-for="val in item.optionItem" :key="val.id"
						style="display: flex;align-items: center;justify-content: space-between;" :class="
					item.userAnswer.isRight == '1' && item.userAnswer.value == val.option
						? 'select'
						: item.userAnswer.isRight == '0' && item.userAnswer.value == val.option
						? 'close'
						: item.userAnswer.value == val.option
						? 'select'
						: ''
				" @click="selectAnswer(item, val)">
						{{val.option + val.content}}
						<uv-icon name="checkmark-circle-fill" color="#36d536" size="28rpx"
							v-if="item.userAnswer.value == val.option && item.userAnswer.isRight != '0'"></uv-icon>
						<uv-icon name="close-circle-fill" color="#ff0000" size="28rpx"
							v-if="item.userAnswer.value == val.option && item.userAnswer.isRight == '0'"></uv-icon>
					</view>
					<view class="btn" @click="submitAnswer(item)" v-if="!item.userAnswer.isRight">
						提交答案
					</view>
				</view>
			</template>
			<view class="nomore" v-if="data.questionList?.length == data.total">没有更多了</view>
		</view>
		<view class="chatHome" v-else>
			<view class="questionList" v-html="data.liveInfo?.introduce">
			</view>
		</view>
	</view>
	<uv-toast ref="toastLayer"></uv-toast>
	<uv-modal ref="videoEnd" content='视频已结束，即将返回首页。' @confirm="videoEndconfirm"></uv-modal>
</template>
<script setup>
	import {
		useglobal
	} from '@/stores'
	import {
		bindLive,
		getliveInfo,
		liveusertopicrecord
	} from '@/api';
	import {
		formatTime
	} from '@/utils/util.js'
	import {
		getCurrentInstance
	} from 'vue';

	const globalData = useglobal();
	const data = reactive({
		userInfo: {},
		liveInfo: {},
		startTime: '',
		liveUrl: '',
		watchNum: 0, //观看人数
		messageList: [], //聊天室信息
		liveId: '', //直播间id
		nowIndex: 0,
		questionList: [{
			title: '题目：如何看湿气？',
			option: [{
					id: 1,
					val: '看肚子'
				},
				{
					id: 2,
					val: '看身材'
				}
			]
		}],
		pwd: '', //密码
		pswNull: '', //如果密码为空则为true
		total: 1,
		isAutoPlay: true,
		isControls: false,
		tvState: 'overNull', //begun未开始  going 进行中 goingNoAnswer直播但是没有答题活动   over 看回放 overNull 回放超时 
		videoCon: {
			img: 'https://cdn.uviewui.com/uview/album/1.jpg',
			title: '国学新建',
			time: '2024-09-08 19:00:09',
			video: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4'
		},
		socketTask: null, //聊天实例
		initMuted: true
	})
	const menu = reactive([
		'活动', '介绍'
	])
	const menuFun = (val) => {
		data.nowIndex = val;
	}
	//回首页
	const backIndex = () => {
		uni.navigateTo({
			url: '/pages/index/index'
		})
	}
	const toastLayer = ref(null);
	const modal = ref(null);
	const MoverTime = ref(null);
	onLoad((option) => {
		//uni.setStorageSync('videoKey', option.key)
		data.liveId = option.liveId;
		data.userInfo = uni.getStorageSync('user_info')
		getlive()
	})

	onUnload(() => {
		wsClose();
		cleanup();
	})

	const cleanup = () => {
		console.log('执行清理操作');
		setTimeout(() => {
			uni.redirectTo({
				url: '/pages/index/index'
			});
		}, 0);
	};

	// 更新当前时间
	const currentTime = ref(null);
	const updateCurrentTime = () => {
		const now = new Date()
		currentTime.value = formatTime(now)
	}

	// 计算直播状态和已直播时间
	const videoTime_seek = ref(null);
	const instance = getCurrentInstance();
	const videoContext = uni.createVideoContext("myVideo", instance);

	//获取直播信息
	const getlive = () => {
		getliveInfo(data.liveId).then(res => {
			//处理一下接口数据的结构
			//--题
			if (res.data.liveUserTopicRecordList && res.data.liveUserTopicRecordList.length) {
				res.data.liveUserTopicRecordList.forEach((el) => {
					el.optionItem = JSON.parse(el.optionItem);
					let userAnswer = {
						value: el.userAnswer ? el.userAnswer : "",
						isRight: "",
					};
					userAnswer.isRight = userAnswer.value ?
						userAnswer.value == el.answer ?
						"1" :
						"0" :
						"";
					el.userAnswer = userAnswer;
				});
			}

			//---图片
			res.data.introduce = res.data.introduce.replace(
				/<img/gi,
				'<img style="max-width:100%;height:auto" ',
			);
			data.questionList = res.data.liveUserTopicRecordList;
			data.total = res.data.topicNum;
			data.liveInfo = res.data;
			data.startTime = res.data.startTime;
			data.liveUrl = res.data.liveUrl;

			uni.setNavigationBarTitle({
				title: res.data.liveName
			})

			connectSocketInit();
		})
	}


	//创建聊天室
	function connectSocketInit() {
		console.log('聊天室参数', data.userInfo.tenantId, data.userInfo.id);
		data.socketTask = uni.connectSocket({
			url: globalData.wssbaseUrl +
				`liveapi/imserver/${data.userInfo.tenantId}/${data.userInfo.id}/${data.liveId}`,
			success(data) {
				console.log("websocket连接成功", data);
				//that.play();
			},
		});
		data.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常打开中...！", res);
			//this.play();	
		});
		data.socketTask.onClose(() => {
			console.log("已经被关闭了");
		});
		data.socketTask.onMessage((res) => {
			wsMessage(res);
			console.log("收到服务器内容：" + res.data);
		});
	}

	function wsClose() {
		data.socketTask.close();
	}

	//观看人数处理
	const wsMessage = (res) => {
		let wsdata = JSON.parse(res.data);
		// 消息类型（1直播间人数变化（进入/退出），2直播间评论，3.直播间点赞，4发送优惠券，5直播间抽奖开启，6直播间抽奖结果，7提出直播间，8直播间公告）
		if (wsdata.msgType == 1 || wsdata.msgType == 2 || wsdata.msgType == 8) {
			data.watchNum = wsdata.liveOnlineNum;
			let obj = {
				text: wsdata.commentContent,
				date: new Date(),
			};
			//data.messageList.unshift(obj);
		}
	}
	const watchNumUnit = computed(() => {
		const num = data.watchNum; // 假设data是reactive对象
		console.log('3', num);
		if (num < 0) return "0"; // 处理负数情况
		if (num < 1000) return num.toString();
		if (num < 10000) return `${(num / 1000).toFixed(1)}k`;
		if (num < 100000) return `${(num / 10000).toFixed(1)}w`;
		return "10w+";
	});
	console.log('观看人数', watchNumUnit.value);
	//答题
	function selectAnswer(item, val) {
		console.log(item, val);
		if (item.userAnswer && item.userAnswer.isRight) {
			return;
		}
		item.userAnswer.value = val.option;
	}

	//提交答案
	async function submitAnswer(item) {
		if (!item.userAnswer.value) {
			uni.showToast({
				title: "请选择答案",
				icon: "none",
			});
			return;
		}
		let para = {
			liveId: data.liveId,
			id: item.id,
			userAnswer: item.userAnswer.value,
			answer: item.answer,
		};
		await liveusertopicrecord(para).then((res) => {
			item.userAnswer.isRight = res.data.flag;
			if (res.data.okFlag == "1") {
				uni.showToast({
					title: "恭喜全部答对",
					icon: "none",
				});
				return;
			}
			uni.showToast({
				title: res.data.msg,
				icon: "none",
				duration: 5000,
			});
		}).catch((err) => {
			item.userAnswer.isRight = "";
		});
	}
	const videoEnd = ref(null);
	const videoEndClick = () => {
		videoContext.exitFullScreen()
		videoEnd.value.open();
		setTimeout(() => {
			uni.redirectTo({
				url: '/pages/index/index'
			});
		}, 3000);
	}
	const videoEndconfirm = () => {
		uni.redirectTo({
			url: '/pages/index/index'
		});
	}
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	.pageBox {
		padding: 0;
		height: 100%;
		display: flex;
		flex-flow: column nowrap;
	}

	.videoBox {
		width: 100%;
	}

	.videoMenu {
		@extend %flex-row-center;
		color: #333;
		font-size: 26rpx;

		&_item {
			width: 50%;
			text-align: center;
			border-bottom: solid 4rpx #fff;
			padding-bottom: 20rpx;
			padding-top: 20rpx;

			&.active {
				border-bottom: solid 4rpx #fc4631;
			}
		}
	}

	.chatHome {
		flex: 1;
		background-color: #efefef;

		.bottom {
			position: fixed;
			bottom: 0;
			padding: 10rpx;
			background-color: #fff;
			width: 100%;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.begun-t {
				color: green;
				font-size: 24rpx;
				font-weight: bold;
			}

			.bottom_left {
				display: flex;
				justify-content: space-between;
				background-color: #efefef;
				flex: 1;
				padding: 10rpx 20rpx;
				margin-right: 30rpx;
				border-radius: 10rpx;
				align-items: center;

				.t {
					color: #666;
					font-size: 24rpx;
				}

				.btn {
					width: fit-content;
					background: #c3c3c3;
					color: #666;
					border: none;
					border-radius: 10rpx;
					padding: 15rpx;
					font-size: 21rpx;
					line-height: 20rpx;
					font-weight: bold;
					cursor: pointer;
				}
			}
		}

		.begunCon {
			margin-top: 100rpx;
			display: flex;
			flex-flow: column nowrap;
			align-items: center;

			.word {
				text-align: center;
				margin-bottom: 20rpx;
				color: #333;

				&.grey {
					color: #999;
					font-size: 24rpx;
				}
			}

			.btn {
				width: fit-content;
				background: #ef4636;
				color: #fff;
				border: none;
				border-radius: 10rpx;
				padding: 20rpx;
				font-size: 24rpx;
				line-height: 30rpx;
				font-weight: bold;
				cursor: pointer;
				text-align: center;
				margin-top: 50rpx;
			}
		}
	}

	.questionList {
		background-color: #fff;
		border-radius: 15rpx;
		margin: 10rpx 20rpx;
		padding: 30rpx;

		.title {
			font-size: 28rpx;
			margin-bottom: 30rpx;
		}

		.option {
			font-size: 26rpx;
			color: #333;
			margin-bottom: 30rpx;
			padding: 10rpx;

			&.select {
				background-color: #36d53660;
			}

			&.close {
				background-color: #ff000050;
			}
		}

		.btn {
			width: 100%;
			background: #ef4636;
			color: #fff;
			border: none;
			border-radius: 10rpx;
			padding: 20rpx 0;
			font-size: 24rpx;
			line-height: 30rpx;
			font-weight: bold;
			cursor: pointer;
			text-align: center;
		}
	}

	.nomore {
		text-align: center;
		color: #999;
		padding: 20rpx 0;
		font-size: 24rpx;
	}

	.videoBox {
		position: relative;

		.person {
			position: absolute;
			background-color: red;
			color: #fff;
			z-index: 555;
			right: 0;
			top: 20rpx;
			padding: 10rpx;
			border-radius: 5rpx;
			font-size: 18rpx;
		}
	}
</style>